package com.park.util;

import org.apache.commons.codec.digest.DigestUtils;

public class DigestUtil {
    private final static int COUNT_INDEX=12;
    private final static int SALT_INDEX=1;
    private final static char[] ITEMS={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
    public static String randomDigest(String pass){
        int randomCountIndex=(int)(Math.random()*ITEMS.length);
        int randomSaltIndex=(int)(Math.random()*ITEMS.length);

        char count=ITEMS[randomCountIndex];
        System.out.println("count:"+count);
        char salt=ITEMS[randomSaltIndex];
        System.out.println("slat:"+salt);
        String result=pass+salt;

        for(int i=0;i<count;i++){
            result=DigestUtils.md5Hex(result);
        }
        System.out.println("result-0:"+result);
        //result就是加密之后的字符串
        result=result.substring(0,SALT_INDEX)+salt+result.substring(SALT_INDEX);
        System.out.println("result-1:"+result);
        result=result.substring(0,COUNT_INDEX)+count+result.substring(COUNT_INDEX);
        System.out.println("result-2:"+result);
        return result;
    }

    public static boolean decode(String pass,String digestPass){
        char salt=digestPass.charAt(SALT_INDEX);
        char count=digestPass.charAt(COUNT_INDEX);

        //开始加密
        String result=pass+salt;
        for (int i = 0; i < count; i++) {
            result=DigestUtils.md5Hex(result);
        }

        result=result.substring(0,SALT_INDEX)+salt+result.substring(SALT_INDEX);
        result=result.substring(0,COUNT_INDEX)+count+result.substring(COUNT_INDEX);

        return result.equals(digestPass);
    }
//    public static void main(String[] args) {
//        //randomDigest("123");
//        boolean b=decode("123","a1f6e96bf7180c05ed3af1439c564ee92e");
//        System.out.println(b);
//    }
}

